#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json

from bottle import Bottle, request, template, view, redirect
from bottle.ext import sqlalchemy

import models
from models import Server, Localservice

serverapp = Bottle()
plugin = sqlalchemy.Plugin(models.engine, models.Base.metadata, create=True)
serverapp.install(plugin)

@serverapp.get('/')
def serverlist(db):

    serverlist = db.query(Server).order_by('sid').all()

    return template("server.html",
                    serverlist = serverlist,
                    appurl = serverapp.appurl)

@serverapp.get('/<sid:re:[0-9\-a-zA-Z]+>')
def serverview(db, sid):
    server = db.query(Server).filter_by(sid=sid).first()
    if server:
        lservice = db.query(Localservice).filter_by(sid=sid).order_by('port').all()
        return template("server.detail.html",
                        server = server,
                        lservice = lservice,
                        appurl = serverapp.appurl)
    return {"status": "404"}

@serverapp.post('/<sid:re:[0-9\-a-zA-Z]+>')
def serverupdate(db, sid):
    server = db.query(Server).filter_by(sid=sid).first()

    if not server:
        server = Server(sid=sid)
        db.add(server)

    if request.forms.name != None:
        server.name = request.forms.name
    if request.forms.location != None:
        server.location = request.forms.location
    if request.forms.eth0_ip != None:
        server.eth0_ip = request.forms.eth0_ip
    if request.forms.eth1_ip != None:
        server.eth1_ip = request.forms.eth1_ip
    if request.forms.rcc_ip != None:
        server.rcc_ip = request.forms.rcc_ip
    if request.forms.machine_info != None:
        server.machine_info = request.forms.machine_info
    if request.forms.cpu_info != None:
        server.cpu_info = request.forms.cpu_info
    if request.forms.mem_info != None:
        server.mem_info = request.forms.mem_info
    if request.forms.hd_info != None:
        server.hd_info = request.forms.hd_info
    if request.forms.os_info != None:
        server.os_info = request.forms.os_info
    if request.forms.kernel_info != None:
        server.kernel_info = request.forms.kernel_info
    if request.forms.desc != None:
        server.desc = request.forms.desc


    redirect(serverapp.appurl + "/" + sid)

@serverapp.post('/<sid:re:[0-9\-a-zA-Z]+>/port')
def serverupdate(db, sid):
    pslist = json.loads(request.forms.pslist)

    lservicelist = db.query(Localservice).filter_by(sid=sid).all()
    for lservice in lservicelist:
        db.delete(lservice)

    for ps in pslist:
        db.add(Localservice(sid=sid,
                            port=ps['port'],
                            servicename=ps['servicename'])
               )

    return {'status':'200'}


@serverapp.get('/_special/port')
def portlist(db):

    portnumbers=[]
    lservicelist = db.query(Localservice).order_by("port").all()
    portnumbers.append(lservicelist[0].port)
    for ls in lservicelist:
        if ls.port != portnumbers[-1]:
            portnumbers.append(ls.port)

    servicelist=[]
    lservicelist = db.query(Localservice).order_by("sid").all()
    servicelist.append({'sid':lservicelist[0].sid, 'port':['' for x in range(len(portnumbers))]})
    for ls in lservicelist:
        if ls.sid != servicelist[-1]['sid']:
            servicelist.append({'sid':ls.sid, 'port':['' for x in range(len(portnumbers))]})
        servicelist[-1]['port'][portnumbers.index(ls.port)] = ls.servicename

    return template("_special.port.html",
                    portnumbers = portnumbers,
                    servicelist = servicelist,
                    appurl = serverapp.appurl)

